<template>
  <el-dialog title="权限修改" :visible.sync="dialogShow" @close="closeDialog">
    <el-tree
      node-key="id"
      show-checkbox
      :data="authList"
      :props="{ label: 'name' }"
      :default-checked-keys="checkAuth"
      :check-strictly="true"
      ref="tree"
    ></el-tree>
    <el-row type="flex" justify="center">
      <el-button @click="setAuthSubmit" size="small" type="primary">
        确定
      </el-button>
      <el-button @click="dialogShow = false" size="small">取消</el-button>
    </el-row>
  </el-dialog>
</template>

<script>
import { getPermissiontListApi } from '@/api/permission'
import { tranListToTreeData } from '@/utils'
import { getRoleInfoApi, setRoleAuthApi } from '@/api/setting'
export default {
  name: 'SetAuth',
  data() {
    return {
      dialogShow: false,
      authList: [], // 所有权限
      checkAuth: [], // 存放选中权限的数据
      roleId: null
    }
  },
  methods: {
    // 获取所有权限
    async getAllAuthList() {
      const res = await getPermissiontListApi()
      this.authList = tranListToTreeData(res, '0')
    },
    // 获取当前角色信息
    async getCurRoleInfo(id) {
      this.roleId = id
      const res = await getRoleInfoApi(id)
      this.checkAuth = res.permIds
    },
    // 角色设置权限提交
    async setAuthSubmit() {
      // this.$refs.tree.getCheckedKeys() 树方法 获取打勾的id
      const permIds = this.$refs.tree.getCheckedKeys()
      if (permIds.length === 0) return this.$message.warning('请勾选节点')
      await setRoleAuthApi({
        id: this.roleId,
        permIds
      })
      this.$message.success('关联权限成功')
      this.dialogShow = false
    },
    closeDialog() {
      this.checkAuth = []
      // 存放选中权限的数据
      this.roleId = null
    }
  }
}
</script>

<style></style>
